<!--
 * @Description: 登录组件
 * @Author: hai-27
 * @Date: 2020-02-19 20:55:17
 * @LastEditors: hai-27
 * @LastEditTime: 2020-03-01 15:34:08
 -->
<template>
  <div id="myLogin">
    <el-dialog title="登录" width="300px" center :visible.sync="isLogin">
      <el-form :model="LoginUser" :rules="rules" status-icon ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user-solid" placeholder="请输入账号" v-model="LoginUser.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请输入密码"
            v-model="LoginUser.password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary"  @click = "login" style="width:100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
	import {
		mapActions
	} from "vuex";
	import userAPI from '../api/user.js'
	import cookie from 'js-cookie'

	export default {
		name: "MyLogin",

		data() {

			// 用户名的校验方法
			let validateName = (rule, value, callback) => {
				if (!value) {
					return callback(new Error("请输入用户名"));
				}
				// 用户名以字母开头,长度在5-16之间,允许字母数字下划线
				const userNameRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
				if (userNameRule.test(value)) {
					this.$refs.ruleForm.validateField("checkPass");
					return callback();
				} else {
					return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
				}
			};

			// 密码的校验方法
			let validatePass = (rule, value, callback) => {
				if (value === "") {
					return callback(new Error("请输入密码"));
				}
				// 密码以字母开头,长度在6-18之间,允许字母数字和下划线
				const passwordRule = /^[a-zA-Z]\w{5,17}$/;
				if (passwordRule.test(value)) {
					this.$refs.ruleForm.validateField("checkPass");
					return callback();
				} else {
					return callback(
						new Error("字母开头,长度6-18之间,允许字母数字和下划线")
					);
				}
			};
			return {
				LoginUser: {
					username: "",
					password: ""
				},
				// 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
				rules: {
					username: [{
						validator: validateName,
						trigger: "blur"
					}],
					password: [{
						validator: validatePass,
						trigger: "blur"
					}]
				}
			}
		},
		computed: {
			// 获取vuex中的showLogin，控制登录组件是否显示
			isLogin: {
				get() {
					return this.$store.getters.getShowLogin;
				},
				set(val) {
					this.$refs["ruleForm"].resetFields();
					this.setShowLogin(val);
				}
			}
		},
		methods: {
			...mapActions(["setUser", "setShowLogin"]),

			login() {
				// TODO element 自定义表单校验规则
				this.$refs["ruleForm"].validate(valid => {
					//如果通过校验开始登录
					if (valid) {
						// TODO 登录API
						userAPI.user_login(this.LoginUser).then(res => {
							const token = res.data
							cookie.set("USER_TOKEN", token, {
								domain: 'localhost'
							}) // 将 token 存在 cookie 中，【也可放入 localStorage 中】
							
							this.getUserInfo()
						}).catch(err => {
							this.notifyError('登陆失败！')
						})
					} else {
						return false;
					}
				})

			},

			// 登录成功后，根据 token 获取用户信息
			async getUserInfo() {
				console.log('USER_TOKEN', cookie.get("USER_TOKEN"))
				let response = await userAPI.user_info() // 请求用户信息				
				this.isLogin = false; // 	// 隐藏登录组件
				const userInfo = {
					userId: response.data.id,
					userName: response.data.username,
					name:response.data.name,
					header:response.data.header,
					sex:response.data.sex,
					userEmail:response.data.userEmail,
					balance:response.data.balance,
				}
				this.setUser(userInfo) // 存 vuex 
				// 登录信息存到本地
				let user = JSON.stringify(userInfo);
				localStorage.setItem("user", user);
				this.notifySucceed('登录成功！');
				this.$router.replace("/")
			}
		}
	}
</script>

<style>
</style>